import 'dart:convert';

import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:extended_keyboard/extended_keyboard.dart';

import '../common/sharedPreferences_helper.dart';
import '../common/emoji_util.dart';
import '../common/special_text/my_special_text_span_builder.dart';
import '../model/emotion_model.dart';

class CommentInputController extends GetxController with GetTickerProviderStateMixin {
  final TextEditingController textEditingController = TextEditingController();
  final MySpecialTextSpanBuilder mySpecialTextSpanBuilder = MySpecialTextSpanBuilder();
  final focusNode = FocusNode();

  var showEmojiPanel = false.obs;
  var sendBtnEnabled = false.obs;
  var emojiMap = {}.obs;
  var selectedIndex = 0.obs;
  var selectedEmotion = "".obs;

  final RxList<EmotionModel> emotionList = <EmotionModel>[].obs;
  double keyboardHeight = 0;

  @override
  void onInit() {
    super.onInit();

    showEmojiPanel.value = Get.arguments["showEmojiPanel"];
    if (!showEmojiPanel.value) {
      focusNode.requestFocus();
    }

    getEmotionList();

    emojiMap.value = EmojiUtil.emojiMap();

    textEditingController.addListener(() {
      sendBtnEnabled.value = textEditingController.text.trim().isNotEmpty;
    });
  }

  @override
  void onClose() {
    focusNode.dispose();
    textEditingController.dispose();
    super.onClose();
  }

  void getEmotionList() {
    final jsonStr = SharedPreferencesHelper.getString("emotionList") ?? '';
    if (jsonStr.isNotEmpty) {
      List<dynamic> emotionJsonList = jsonDecode(jsonStr);
      List<EmotionModel> emotionList = emotionJsonList.map((json) => EmotionModel.fromJson(json)).toList();
      this.emotionList.clear();
      this.emotionList.addAll(emotionList);
    }
  }

  void addEmoji(String k) {
    textEditingController.insertText(k);
  }

  void deleteText() {
    final TextSpan oldTextSpan = mySpecialTextSpanBuilder.build(textEditingController.text);
    final TextEditingValue value = ExtendedTextLibraryUtils.handleSpecialTextSpanDelete(
      textEditingController.deleteText(),
      textEditingController.value,
      oldTextSpan,
      null,
    );
    textEditingController.value = value;
  }

  onSubmitComment() {
    print(textEditingController.text);
  }
}
